<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */ 
namespace app\web\controller;

use app\common\Base;
use \think\Image;
class Account extends Base{

    public function __construct() {
            parent::__construct();
            if(!$this->is_login)
                $this->error_ui('请先登录');
    }

    public function my_array_sub($all, $ac) {
        $tmp_all = array();
        $res = array();
        foreach ($ac as $key => $value) {
            $tmp_all[$value['problem_id']] = 1;
        }
        foreach ($all as $key => $value) {
            if(!isset($tmp_all[$value['problem_id']]))
                $res[] = $value['problem_id'];
        }
        return $res;
    }
    public function info() {
        $user_id=input('user_id');
        $result = db('users')->where(['user_id' => $user_id])->select();
        $all_pid = db('solution')->where(['user_id'=>$user_id])->order('problem_id asc')->distinct('true')->field('problem_id')->select();
        $ac_pid = db('solution')->where(['user_id' => $user_id ,'result' => 4])->order('problem_id asc')->distinct('true')->field('problem_id')->select();
        $none_pid = $this->my_array_sub($all_pid, $ac_pid);
        // $notac_pid=db('solution')->where()
        if(empty($result)) {
            $this->error_ui('此用户不存在!');
            return ;
        }
        $img = $result[0]['head'];
        $email_power=false;  //能否查看用户邮箱
        if($this->user_id == $user_id || $this->have_power(8)) {
        $email_power=true; //如果是本人或者是拥有权限8（用户管理权限）的话，就可以查看所有用户的邮箱。
        }
        $this->assign('email_power',$email_power);
        $this->assign('ac_pid',$ac_pid);//ac的题的题号
        $this->assign('count_ac',count($ac_pid));//ac的题的数量
        $this->assign('none_pid',$none_pid); //未ac的题的题号
        $this->assign('count_none',count($none_pid));//未AC题目的数量
        $this->assign('img',$img);
        $this->assign('coin',$result[0]['ojcoin']);
        $this->assign('user_id',$result[0]['user_id']);
        $this->assign('email',$result[0]['email']);
        $this->assign('nick',htmlspecialchars($result[0]['nick']));
        $this->assign('school', htmlspecialchars($result[0]['school']));
        $this->assign('qq',htmlspecialchars($result[0]['qq']));
        $this->assign('blog',htmlspecialchars($result[0]['blog']));
        $this->assign('brief',htmlspecialchars($result[0]['brief']));
        return $this->fetch();
    }
    public function alterinfo() {
        $user_id=$this->user_id;
        $result = db('users')->where(['user_id' => $user_id])->select();
        // $this->assign('s',ROOT_PATH);
        $this->assign('src',$result[0]['head']);
        $this->assign('user_id',$result[0]['user_id']);
        $this->assign('email',$result[0]['email']);
        $this->assign('nick',htmlspecialchars($result[0]['nick']));
        $this->assign('school', htmlspecialchars($result[0]['school']));
        $this->assign('qq',htmlspecialchars($result[0]['qq']));
        $this->assign('blog',htmlspecialchars($result[0]['blog']));
        $this->assign('brief',htmlspecialchars($result[0]['brief']));
        // $this->assign('nick',$result[0]['nick']);
        // $this->assign('school',$result[0]['school']);
        // $this->assign('qq',$result[0]['qq']);
        // $this->assign('blog',$result[0]['blog']);
        // $this->assign('brief',$result[0]['brief']);
        return $this->fetch();
    }
    public function upload_picture() {
        $file=request()->file('file');
        $url_load = db('users')->where(['user_id' => $this->user_id ])->field('head')->select();
        
        $info = $file->validate(['size'=>2097152,'ext'=>'jpg,png,gif'])->move(ROOT_PATH . 'public/upload/users/head/');
        if($info) {
            if($url_load[0]['head']!='default.png') { 
                if(is_file(ROOT_PATH . 'public/upload/users/head/' . $url_load[0]['head'])) {
                    unlink(ROOT_PATH . 'public/upload/users/head/' . $url_load[0]['head']);
                }
            }
            $user['head'] = $info->getSaveName();
            $user['user_id'] = $this->user_id;
            db('users')->update($user);
            $image =Image::open(ROOT_PATH . 'public/upload/users/head/'.$user['head']);
            $image->thumb(300,300,Image::THUMB_CENTER)->save(ROOT_PATH . 'public/upload/users/head/'.$user['head']);
            // $path = $info->getExtension();
            // $src = ROOT_PATH . 'public/upload/users/head/'.$user['head'];
            // dump($path);

            return json(array('state'=>1,'src'=>$user['head']));
        } else    {
            // 上传失败获取错误信息
            // echo $file->getError();
            return json(array('state'=>0));
        }
    }
    public function submitalter() {
        $user = Array();
        $user['user_id'] = $this->user_id;
        $user['nick'] = $this->remove_xss(input('post.nick'));
        $user['school'] = $this->remove_xss(input('post.school'));
        $user['qq'] = $this->remove_xss(input('post.qq'));
        $user['blog'] = $this->remove_xss(input('post.blog'));
        $user['brief'] = $this->remove_xss(input('post.brief'));
        db('users')->update($user);
        $this->success_ui('修改信息成功！',url('web/account/info',['user_id' => $this->user_id]));
    }
    public function AlterPasswd() {
        // dump(md5(config('login') . md5('123456') . 'hsdm'));
        return $this->view->fetch();
    }
    public function JudgePassword() {
        $user = Array();
        $user['user_id'] = $this->user_id;
        $user['password'] = input('post.password');
        $user['password'] = md5(config('login') . md5($user['password']) . $user['user_id']);
        $result = db('users')->where($user)->find();
        // return db('users')->fetchSql(1)->where($user)->find();
        if(empty($result)) return json(['result'=>false]);//输入密码错误
        $user['password'] = md5(config('login') . md5(input('password1')) . $user['user_id']);
        db('users')->update($user);
        return json(['result'=>true]);//输入密码正确
    }

    // 导入旧版本OJ的提交记录
    public function regression() {
        return $this->fetch();
    }
    public function do_regression(){
        if($this->is_login == false){
            $this->error_ui("你还没有登录",3);
        }
        $user['userid']=input('post.user_id');
        $password = input('post.password');
        $user['password']=md5($password);
        $find = db('ojuser')->where($user)->find();
        if(empty($find)) { //密码输入错误
            $this->error_ui("旧版OJ,账号名或密码错误",3);
        } else if($this->mutex_get()>=3) {
            
        }
        else {
            $this->mutex_update(1);
            $this->update_submit($user['userid'],$this->user_id);
            $this->mutex_update(-1);
            $this->success_ui("导入成功~",url('web/Problem/problemset'));
        }
    }
    private function update_submit($old_userID, $new_userID){
        $once_update_count = 100;
        while(true){
            $data = db('status')->where(['userid'=>$old_userID])->limit(0,$once_update_count)->select();
            if(empty($data)) 
                break;
            foreach ($data as $k=>$v){
                $insert_data=array();
                //提交语言更新
                if ($v['language'] == "C/C++") { 
                    $insert_data['language'] = 1;
                } else if ($v['language'] == "JAVA") {
                    $insert_data['language'] = 3;
                }

                //提交结果更新
                if ($v['result'] == "Accepted") {
                    $insert_data['result'] = 4;
                } else if ($v['result'] == "WrongAnswer") {
                    $insert_data['result'] = 6;
                } else if ($v['result'] == "RuntimeError") {
                    $insert_data['result'] = 10;
                } else if ($v['result'] == "TimeLimitExceeded") {
                    $insert_data['result'] = 7;
                } else if ($v['result'] == "MemoryLimitExceeded") {
                    $insert_data['result'] = 8;
                } else if ($v['result'] == "OutputLimitExceeded") {
                    $insert_data['result'] = 9;
                } else if ($v['result'] == "SystemError") { //系统错误也为运行时错误
                    $insert_data['result'] = 10;
                } else if ($v['result'] == "CompileError") {
                    $insert_data['result'] = 11;
                }
                else {
                    $insert_data['result'] = 6;
                }

                $insert_data['problem_id'] = $v['pid'];
                $insert_data['user_id'] = $new_userID;
                $insert_data['time'] = $v['timecost'];
                $insert_data['memory'] = $v['memorycost'];
                $insert_data['in_date'] = $v['submittime'];
                $insert_data['ip'] = $v['127.0.0.1'];
                $insert_data['contest_id'] = null;
                $insert_data['valid'] = 1;
                $insert_data['num'] = -1;
                $insert_data['code_length'] = strlen($v['code']);
                $insert_data['judgetime'] = $v['submittime'];
                $insert_data['pass_rate'] = $insert_data['result']==4?1.00:0.0;
                $insert_data['lint_error'] = 0;
                $insert_data['judger'] = '旧版OJ';
                $sid=db('solution')->insert($insert_data,false,true);
                $codedata['solution_id']=$sid;
                $codedata['source']=$v['code'];
                db('source_code')->insert($codedata);
                db('status')->delete($v['runid']);
            }
        }
    }

    //老OJ数据转向新OJ，功能已基本实现，先不提交，
    public function update_submit_bak() {
        $data = db('regression')->where(['status'=>0])->select();
        // dump($data);
        
    }

    public function test()
    {
        $this->mutex_update(1);
        dump($this->mutex_get());
    }
}

